import requests
import json, cv2
from base64 import b64decode, b64encode
import numpy as np
import logging
import shutil, os


def post_rooftop_old(img_file_path="data/1710231844212.jpg"):
    file_name = os.path.basename(img_file_path)
    img_data = cv2.imread(img_file_path)
    shape = img_data.shape[:2]
    max_size = 1920
    scale = max(max(shape) / max_size, 1)
    new_shape = [int(shape[1] / scale) // 2 * 2, int(shape[0] / scale) // 2 * 2]
    img_data = cv2.resize(img_data, new_shape)
    ret, img_encode = cv2.imencode(".jpg", img_data)
    img_byte = img_encode.tobytes()
    img_str = str(b64encode(img_byte), "utf-8")
    json_data = {
        "id": 75,
        "mode": "b64",
        "image": img_str,
        "clas": "rs",
    }
    # json_data = {
    #     "id":74,
    #     "mode":"restart",
    #     "image": img_str,
    #     "clas": "",

    # }
    url = "http://0.0.0.0:12682/api/V1.0/rooftop"
    # url = "http://183.4.99.47:12682/api/V1.0/rooftop"

    response = requests.post(url=url, json=json_data)
    response = json.loads(response.text)
    print(response)
    bboxes = response["data"][0][1]["points"]
    h, w, _ = img_data.shape
    for boxes in bboxes:
        boxes = [[int(x[0] * w), int(x[1] * h)] for x in boxes]
        pts = np.array(boxes, np.int32)
        pts = pts.reshape([-1, 1, 2])
        cv2.polylines(img_data, [pts], isClosed=True, color=(0, 0, 255), thickness=3)
    if not os.path.exists("data/output/rooftop"):
        os.makedirs("data/output/rooftop")
    cv2.imwrite("data/output/rooftop/{}".format(file_name), img_data)

    print("")
    # vis = cv2.imdecode(np.frombuffer(b64decode(response["image"]),np.uint8),1)
    # cv2.imwrite("data/output/{}".format(img_file_path.rsplit("/",1)[-1]),vis)
    # vis = cv2.imdecode(np.frombuffer(b64decode(response["data"]["mask"]),np.uint8),cv2.IMREAD_GRAYSCALE)
    # cv2.imwrite("temp2.jpg",vis)
    # with open("data/output/temp_file.json","w") as f:
    # json.dump(response,f)


def post_rooftop(img_file_path="data/1710231844212.jpg"):
    img_data = cv2.imread(img_file_path)
    ret, img_encode = cv2.imencode(".jpg", img_data)
    img_byte = img_encode.tobytes()
    img_str = str(b64encode(img_byte), "utf-8")
    json_data = {"id": 75, "tag": "pop", "data": img_str}
    url = "http://0.0.0.0:2682/api/task/rooftop"
    response = requests.post(url=url, json=json_data)
    response = json.loads(response.text)
    print(response)
    bboxes = response["data"][0][1]["points"]
    h, w, _ = img_data.shape
    for boxes in bboxes:
        boxes = [[int(x[0] * w), int(x[1] * h)] for x in boxes]
        pts = np.array(boxes, np.int32)
        pts = pts.reshape([-1, 1, 2])
        cv2.polylines(
            img_data, [pts], isClosed=True, color=(255, 255, 255), thickness=3
        )
    cv2.imwrite("temp.jpg", img_data)

    print("")
    # vis = cv2.imdecode(np.frombuffer(b64decode(response["image"]),np.uint8),1)
    # cv2.imwrite("data/output/{}".format(img_file_path.rsplit("/",1)[-1]),vis)
    # vis = cv2.imdecode(np.frombuffer(b64decode(response["data"]["mask"]),np.uint8),cv2.IMREAD_GRAYSCALE)
    # cv2.imwrite("temp2.jpg",vis)
    # with open("data/output/temp_file.json","w") as f:
    # json.dump(response,f)


def post_restart():

    url = "http://0.0.0.0:2682/api/V1.0/rooftop"

    json_data = {
        "id": 76,
        "mode": "restart",
        "image": "",
        "clas": "",
    }

    response = requests.post(url=url, json=json_data)
    print(response)


def get_log():

    url = "http://0.0.0.0:2682/api/V1.0/getLog"

    response = requests.get(url=url)
    json_response = json.loads(response.text)
    print("")


if __name__ == "__main__":
    import glob

    # for file_path in glob.glob("/home/smartgis/workspace/data/rooftop/1/labelme/data/*.jpg"):
    #     post_rooftop(file_path)
    import threading

    for root, dirs, files in os.walk("data/input/rooftop/uav"):
        for file_name in files:
            post_rooftop_old(
                root + "/" + file_name,
            )
    # post_rooftop()
    # post_restart()
    # get_log()
